<template>
  <div class="editor-overlay" v-if="showEditor">
    <div class="editor-dialog">
      <div class="editor-header">
        <h3>编辑店铺信息</h3>
        <button class="close-btn" @click="closeEditor">&times;</button>
      </div>
      <div class="editor-content">
        <form @submit.prevent="saveChanges">
          <div class="form-group">
            <label>名称:</label>
            <input v-model="currentVenue.store_name" required />
          </div>
          <div class="form-group">
            <label>法人身份证:</label>
            <input v-model="currentVenue.legal_person_id_card" required />
          </div>
          <div class="form-group">
            <label>是否放心场所:</label>
            <div class="custom-select" @click.stop>
              <div class="select-header" @click="isTagDropdownOpen = !isTagDropdownOpen">
                <span>{{ currentVenue.reassured || '选择标签' }}</span>
                <i class="arrow-icon" :class="{ 'open': isTagDropdownOpen }">&#9660;</i>
              </div>
              <div class="select-options" v-if="isTagDropdownOpen">
                <div class="option-item" @click="handleTagSelect('')">请选择标签</div>
                <div 
                  class="option-item" 
                  v-for="tag in venueReassured" 
                  :key="tag"
                  @click="handleTagSelect(tag)"
                  :class="{ 'selected': currentVenue.reassured === tag }"
                >
                  {{ tag }}
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>类型:</label>
            <div class="custom-select" @click.stop>
              <div class="select-header" @click="isTypeDropdownOpen = !isTypeDropdownOpen">
                <span>{{ currentVenue.type || '选择场所类型' }}</span>
                <i class="arrow-icon" :class="{ 'open': isTypeDropdownOpen }">&#9660;</i>
              </div>
              <div class="select-options" v-if="isTypeDropdownOpen">
                <div class="option-item" @click="handleTypeSelect('')">请选择场所类型</div>
                <div 
                  class="option-item" 
                  v-for="type in venueTypes" 
                  :key="type"
                  @click="handleTypeSelect(type)"
                  :class="{ 'selected': currentVenue.type === type }"
                >
                  {{ type }}
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>状态:</label>
            <div class="custom-select" @click.stop>
              <div class="select-header" @click="isStatusDropdownOpen = !isStatusDropdownOpen">
                <span>{{ currentVenue.status || '选择营业状态' }}</span>
                <i class="arrow-icon" :class="{ 'open': isStatusDropdownOpen }">&#9660;</i>
              </div>
              <div class="select-options" v-if="isStatusDropdownOpen">
                <div class="option-item" @click="handleStatusSelect('')">请选择营业状态</div>
                <div 
                  class="option-item" 
                  v-for="status in statusTypes" 
                  :key="status"
                  @click="handleStatusSelect(status)"
                  :class="{ 'selected': currentVenue.status === status }"
                >
                  {{ status }}
                </div>
              </div>
            </div>
          </div>
          <div class="filter-item">
            <label>所属街道:</label>
            <div class="custom-select" @click.stop>
              <div class="select-header" @click="isStreetDropdownOpen = !isStreetDropdownOpen">
                <span>{{ selectedStreet || '选择街道' }}</span>
                <i class="arrow-icon" :class="{ 'open': isStreetDropdownOpen }">&#9660;</i>
              </div>
              <div class="select-options" v-if="isStreetDropdownOpen">
                <div class="option-item" @click="handleStreetSelect('')">全部</div>
                <div class="option-item" v-for="street in streets" :key="street"
                  @click="handleStreetSelect(street)" :class="{ 'selected': selectedStreet === street }">
                  {{ street }}
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>位置类型:</label>
            <div class="custom-select" @click.stop>
              <div class="select-header" @click="isLocationTypeDropdownOpen = !isLocationTypeDropdownOpen">
                <span>{{ currentVenue.location_type || '选择位置类型' }}</span>
                <i class="arrow-icon" :class="{ 'open': isLocationTypeDropdownOpen }">&#9660;</i>
              </div>
              <div class="select-options" v-if="isLocationTypeDropdownOpen">
                <div class="option-item" @click="handleLocationTypeSelect('')">请选择位置类型</div>
                <div 
                  class="option-item" 
                  v-for="type in locationTypes" 
                  :key="type"
                  @click="handleLocationTypeSelect(type)"
                  :class="{ 'selected': currentVenue.location_type === type }"
                >
                  {{ type }}
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>地址:</label>
            <input v-model="currentVenue.address" required />
          </div>
          <div class="form-group">
            <label>经度:</label>
            <input v-model.number="currentVenue.longitude" type="number" step="0.000001" required />
          </div>
          <div class="form-group">
            <label>纬度:</label>
            <input v-model.number="currentVenue.latitude" type="number" step="0.000001" required />
          </div>
          <div class="form-group">
            <label>店铺图片:</label>
            <div class="upload-container">
              <input type="file" id="fileUpload" class="file-input" ref="fileInput" accept="image/*" multiple @change="handleFileChange" />
            <label for="fileUpload" class="upload-btn" :class="{ 'disabled': isUploading }"><span v-if="!isUploading">选择图片</span><span v-if="isUploading">上传中...</span></label>
              <p class="upload-tip">支持多张图片上传，格式为jpg、png，大小不超过5MB</p>
              <div class="progress-container" v-if="isUploading">
                <div class="progress-bar" :style="{ width: uploadProgress * 100 + '%' }"></div>
                <span class="progress-text">{{ Math.floor(uploadProgress * 100) }}%</span>
              </div>
              <div class="file-names" v-show="fileNames.length > 0">
                <div v-for="(name, index) in fileNames" :key="index" class="file-name-item">
                  <span>{{ name }}</span>
                  <button class="remove-file" @click="removeImage(index)">&times;</button>
                </div>
              </div>
            </div>
          </div>
          <div class="editor-actions">
            <button type="button" class="cancel-btn" @click="closeEditor">取消</button>
            <button type="submit" class="save-btn">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, onUnmounted } from 'vue';
import { uploadFile } from '../utils/ossUpload.js'

const uploadController = new AbortController();

onUnmounted(() => {
  uploadController.abort();
});
import { ossUploadFolder } from '../utils/config.js'

const props = defineProps({
  showEditor: {
    type: Boolean,
    required: true
  },
  currentVenue: {
    type: Object,
    required: true
  },
  venueReassured: {
    type: Array,
    required: true
  },
  venueTypes: {
    type: Array,
    required: true
  },
  statusTypes: {
    type: Array,
    required: true
  },

  streets: {
    type: Array,
    required: true
  }
});

const emits = defineEmits(['close', 'save']);
const venue = ref({
  ...props.currentVenue,
  photoName: props.currentVenue.photoName ? props.currentVenue.photoName.split(',') : []
});

const fileInput = ref(null)
const fileNames = ref([...venue.value.photoName])
const isUploading = ref(false)
const uploadProgress = ref(0)



const handleFileChange = (e) => {
  const files = e.target.files
  if (files.length && !isUploading.value) {
    Array.from(files).forEach(file => {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请上传图片文件');
        return;
      }
      // 验证文件大小（5MB）
      if (file.size > 5 * 1024 * 1024) {
        alert('文件大小不能超过5MB');
        return;
      }
      uploadImage(file)
    })
    e.target.value = ''
  }
}

const uploadImage = async (file) => {
  isUploading.value = true
  try {
    const result = await uploadFile(file, ossUploadFolder, (progress) => {
      uploadProgress.value = progress
    })
    venue.value.photoName.push(result.name)
    fileNames.value.push(file.name)
    alert('图片上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    let errorMessage = '图片上传失败，请重试'
    if (error.message.includes('401')) {
      errorMessage = '认证失败，请重新登录'
    } else if (error.message.includes('413')) {
      errorMessage = '文件过大，服务器拒绝处理'
    } else if (error.message.includes('网络错误')) {
      errorMessage = '网络连接失败，请检查网络后重试'
    }
    alert(errorMessage)
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

const removeImage = (index) => {
  // 如果是已上传的图片，可能需要调用后端API删除
  // 这里仅做前端预览移除
  fileNames.value.splice(index, 1)
  venue.value.photoName.splice(index, 1)
}

const closeEditor = () => {

  emits('close')
}
const currentVenue = venue;

const isTypeDropdownOpen = ref(false);
const isStatusDropdownOpen = ref(false);
const isStreetDropdownOpen = ref(false);
const isLocationTypeDropdownOpen = ref(false);
const isTagDropdownOpen = ref(false);
const selectedStreet = ref('');
const selectedReassured = ref('');

const locationTypes = ref([
  '沿街店铺',
  '纯沿街店铺',
  '纯小区住宅内',
  '高层住宅下沿街店铺',
  '楼宇内',
  '纯商业楼内',
  '楼宇',
]);

// 初始化选中的街道
if (currentVenue.value.policeStation) {
  selectedStreet.value = currentVenue.value.policeStation;
}
// 初始化选中的放心场所
if (currentVenue.value.reassured) {
  selectedReassured.value = currentVenue.value.reassured;
}




const handleTypeSelect = (type) => {
  currentVenue.value.type = type;
  isTypeDropdownOpen.value = false;
};

const handleStatusSelect = (status) => {
  currentVenue.value.status = status;
  isStatusDropdownOpen.value = false;
};

const handleStreetSelect = (street) => {
  selectedStreet.value = street;
  currentVenue.value.policeStation = street;
  isStreetDropdownOpen.value = false;
};

const handleLocationTypeSelect = (type) => {
  currentVenue.value.location_type = type;
  isLocationTypeDropdownOpen.value = false;
};

const handleTagSelect = (tag) => {
  currentVenue.value.reassured = tag;
  isTagDropdownOpen.value = false;
};


const saveChanges = () => {
  emits('save', {...currentVenue.value});
};
</script>

<style scoped>
.filter-item label {
  font-size: 14px;
  display: block;
  margin-bottom: 5px;
  color: #00f0ff;
  text-shadow: 0 0 3px rgba(0, 240, 255, 0.5);
}

.filter-item select {
  width: 100%;
  padding: 8px;
  border: 1px solid rgba(0, 240, 255, 0.3);
  border-radius: 6px;
  background: rgba(30, 41, 59, 0.7);
  color: #e2e8f0;
  margin-top: 5px;
  transition: all 0.3s ease;
}

.filter-item select:focus {
  outline: none;
  border-color: #00f0ff;
  box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
}

/* 选择框选项样式 */
.filter-item select option {
  background-color: #1e293b;
  color: #e2e8f0;
}
.upload-container {
  margin-top: 10px;
}

.file-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  z-index: -1;
}

.upload-btn {
  display: inline-block;
  padding: 8px 16px;
  background: rgba(0, 240, 255, 0.2);
  border: 1px solid rgba(0, 240, 255, 0.5);
  border-radius: 6px;
  color: #00f0ff;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-btn:hover:not(.disabled) {
  background: rgba(0, 240, 255, 0.3);
  box-shadow: 0 0 8px rgba(0, 240, 255, 0.4);
}

.upload-btn.disabled {
  opacity: 0.7;
  cursor: not-allowed;
  background: rgba(30, 41, 59, 0.5);
}

.upload-tip {
  margin: 8px 0 0 0;
  color: rgba(226, 232, 240, 0.7);
  font-size: 12px;
}

.progress-container {
  width: 100%;
  height: 8px;
  background: rgba(30, 41, 59, 0.5);
  border-radius: 4px;
  margin-top: 10px;
  overflow: hidden;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, rgba(0,240,255,0.3) 0%, rgba(0,240,255,0.8) 100%);
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  right: 10px;
  top: -18px;
  font-size: 12px;
  color: #00f0ff;
}

.file-names {
  margin-top: 15px;
}

.file-name-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: rgba(30, 41, 59, 0.5);
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 14px;
}

.remove-file {
  background: rgba(239, 68, 68, 0.2);
  border: 1px solid rgba(239, 68, 68, 0.5);
  color: #ef4444;
  border-radius: 4px;
  cursor: pointer;
  padding: 2px 6px;
  font-size: 12px;
  transition: all 0.3s;
}

.remove-file:hover {
  background: rgba(239, 68, 68, 0.3);
}
.editor-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.editor-dialog {
  background: rgba(15, 23, 42, 0.95);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 240, 255, 0.3);
  border: 1px solid rgba(0, 240, 255, 0.3);
  width: 450px;
  padding: 25px;
  max-width: 90%;
  color: #e2e8f0;
  background-image: radial-gradient(rgba(0, 240, 255, 0.15) 1px, transparent 1px);
  background-size: 20px 20px;
  margin-top: -50px;
}

.editor-header {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 240, 255, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-header h3 {
  margin: 0;
  color: #00f0ff;
  text-shadow: 0 0 8px rgba(0, 240, 255, 0.5);
}

.close-btn {
  background: none;
  border: none;
  color: #e2e8f0;
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.close-btn:hover {
  color: #00f0ff;
}

.editor-content {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
  box-sizing: border-box;
}

.editor-content::-webkit-scrollbar {
  width: 6px;
}

.editor-content::-webkit-scrollbar-track {
  background: rgba(30, 41, 59, 0.5);
  border-radius: 10px;
}

.editor-content::-webkit-scrollbar-thumb {
  background: rgba(0, 240, 255, 0.3);
  border-radius: 10px;
}

.editor-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 240, 255, 0.5);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #00f0ff;
  text-shadow: 0 0 3px rgba(0, 240, 255, 0.5);
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  height: 36px;
  box-sizing: border-box;
  border: 1px solid rgba(0, 240, 255, 0.3);
  border-radius: 6px;
  background: rgba(30, 41, 59, 0.7);
  color: #e2e8f0;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #00f0ff;
  box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
}

/* 自定义下拉选择器样式 */
.custom-select {
  position: relative;
  width: 100%;
  margin-top: 5px;
}

.select-header {
  padding: 8px;
  height: 36px;
  box-sizing: border-box;
  border: 1px solid rgba(0, 240, 255, 0.3);
  border-radius: 6px;
  background: rgba(30, 41, 59, 0.7);
  color: #e2e8f0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s ease;
}

.select-header:hover {
  border-color: #00f0ff;
  box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
}

.arrow-icon {
  transition: transform 0.3s ease;
  font-size: 12px;
}

.arrow-icon.open {
  transform: rotate(180deg);
}

.select-options {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(15, 23, 42, 0.95);
  border: 1px solid rgba(0, 240, 255, 0.3);
  border-radius: 0 0 6px 6px;
  max-height: 250px;
  overflow-y: auto;
  z-index: 10;
  margin-top: -1px;
  box-shadow: 0 5px 15px rgba(0, 240, 255, 0.15);
}

.option-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.option-item:hover {
  background: rgba(0, 240, 255, 0.2);
}

.option-item.selected {
  background: rgba(0, 240, 255, 0.3);
  font-weight: bold;
}

.suboffice-group {
  border-top: 1px solid rgba(0, 240, 255, 0.1);
}

.suboffice-header {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(30, 41, 59, 0.5);
}

.expand-icon {
  font-size: 12px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stations-list {
  padding-left: 15px;
}

.station-item {
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.station-item:hover {
  background: rgba(0, 240, 255, 0.2);
  padding-left: 15px;
}

.station-item.selected {
  background: rgba(0, 240, 255, 0.3);
  font-weight: bold;
}

/* 自定义滚动条 */
.select-options::-webkit-scrollbar {
  width: 6px;
}

.select-options::-webkit-scrollbar-track {
  background: rgba(30, 41, 59, 0.5);
  border-radius: 10px;
}

.select-options::-webkit-scrollbar-thumb {
  background: rgba(0, 240, 255, 0.3);
  border-radius: 10px;
}

.select-options::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 240, 255, 0.5);
}

.editor-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 25px;
  padding-top: 15px;
  border-top: 1px solid rgba(0, 240, 255, 0.1);
}

.cancel-btn,
.save-btn {
  width: 100px;
  height: 36px;
  padding: 0;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(0, 240, 255, 0.3);
  color: #e2e8f0;
}

.save-btn {
  background: rgba(0, 240, 255, 0.2);
  border: 1px solid rgba(0, 240, 255, 0.5);
  color: #00f0ff;
}

.cancel-btn:hover {
  background: rgba(30, 41, 59, 1);
}

.save-btn:hover {
  background: rgba(0, 240, 255, 0.3);
  box-shadow: 0 0 8px rgba(0, 240, 255, 0.4);
  border-color: #00f0ff;
}
</style>